// 游戏配置
const config = {
    canvasWidth: 400,
    canvasHeight: 400,
    gridSize: 20,
    initialSpeed: 150,
    speedIncrease: 10
};

// 游戏状态
let gameState = {
    snake: [],
    food: {},
    direction: 'right',
    nextDirection: 'right',
    score: 0,
    highScore: localStorage.getItem('snakeHighScore') || 0,
    gameRunning: false,
    gamePaused: false,
    gameLoop: null
};

// DOM元素
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const highScoreElement = document.getElementById('high-score');
const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');
const restartBtn = document.getElementById('restartBtn');
const gameOverModal = document.getElementById('gameOverModal');
const finalScoreElement = document.getElementById('finalScore');
const playAgainBtn = document.getElementById('playAgainBtn');

// 初始化游戏
function initGame() {
    // 初始化蛇
    gameState.snake = [
        {x: 5, y: 10},
        {x: 4, y: 10},
        {x: 3, y: 10}
    ];
    
    // 生成食物
    generateFood();
    
    // 重置游戏状态
    gameState.direction = 'right';
    gameState.nextDirection = 'right';
    gameState.score = 0;
    gameState.gameRunning = false;
    gameState.gamePaused = false;
    
    // 更新显示
    updateScore();
    highScoreElement.textContent = gameState.highScore;
    
    // 绘制初始画面
    draw();
}

// 生成食物
function generateFood() {
    let newFood;
    do {
        newFood = {
            x: Math.floor(Math.random() * (config.canvasWidth / config.gridSize)),
            y: Math.floor(Math.random() * (config.canvasHeight / config.gridSize))
        };
    } while (gameState.snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));
    
    gameState.food = newFood;
}

// 绘制游戏
function draw() {
    // 清空画布
    ctx.fillStyle = '#f0f0f0';
    ctx.fillRect(0, 0, config.canvasWidth, config.canvasHeight);
    
    // 绘制网格（可选）
    ctx.strokeStyle = '#ddd';
    ctx.lineWidth = 0.5;
    for (let i = 0; i <= config.canvasWidth; i += config.gridSize) {
        ctx.beginPath();
        ctx.moveTo(i, 0);
        ctx.lineTo(i, config.canvasHeight);
        ctx.stroke();
    }
    for (let i = 0; i <= config.canvasHeight; i += config.gridSize) {
        ctx.beginPath();
        ctx.moveTo(0, i);
        ctx.lineTo(config.canvasWidth, i);
        ctx.stroke();
    }
    
    // 绘制蛇
    gameState.snake.forEach((segment, index) => {
        if (index === 0) {
            // 蛇头
            ctx.fillStyle = '#4CAF50';
        } else {
            // 蛇身
            ctx.fillStyle = '#81C784';
        }
        
        ctx.fillRect(
            segment.x * config.gridSize,
            segment.y * config.gridSize,
            config.gridSize - 2,
            config.gridSize - 2
        );
    });
    
    // 绘制食物
    ctx.fillStyle = '#FF5722';
    ctx.beginPath();
    ctx.arc(
        gameState.food.x * config.gridSize + config.gridSize / 2,
        gameState.food.y * config.gridSize + config.gridSize / 2,
        config.gridSize / 2 - 2,
        0,
        2 * Math.PI
    );
    ctx.fill();
}

// 更新游戏状态
function update() {
    if (!gameState.gameRunning || gameState.gamePaused) return;
    
    // 更新方向
    gameState.direction = gameState.nextDirection;
    
    // 计算新的蛇头位置
    const head = {...gameState.snake[0]};
    
    switch (gameState.direction) {
        case 'up':
            head.y -= 1;
            break;
        case 'down':
            head.y += 1;
            break;
        case 'left':
            head.x -= 1;
            break;
        case 'right':
            head.x += 1;
            break;
    }
    
    // 检查碰撞
    if (checkCollision(head)) {
        gameOver();
        return;
    }
    
    // 添加新的蛇头
    gameState.snake.unshift(head);
    
    // 检查是否吃到食物
    if (head.x === gameState.food.x && head.y === gameState.food.y) {
        gameState.score += 10;
        updateScore();
        generateFood();
        
        // 增加速度
        if (gameState.score % 50 === 0) {
            clearInterval(gameState.gameLoop);
            const newSpeed = Math.max(50, config.initialSpeed - Math.floor(gameState.score / 50) * config.speedIncrease);
            gameState.gameLoop = setInterval(gameStep, newSpeed);
        }
    } else {
        // 移除蛇尾
        gameState.snake.pop();
    }
    
    draw();
}

// 检查碰撞
function checkCollision(head) {
    // 检查墙壁碰撞
    if (head.x < 0 || head.x >= config.canvasWidth / config.gridSize ||
        head.y < 0 || head.y >= config.canvasHeight / config.gridSize) {
        return true;
    }
    
    // 检查自身碰撞
    for (let i = 1; i < gameState.snake.length; i++) {
        if (head.x === gameState.snake[i].x && head.y === gameState.snake[i].y) {
            return true;
        }
    }
    
    return false;
}

// 更新分数
function updateScore() {
    scoreElement.textContent = gameState.score;
    if (gameState.score > gameState.highScore) {
        gameState.highScore = gameState.score;
        highScoreElement.textContent = gameState.highScore;
        localStorage.setItem('snakeHighScore', gameState.highScore);
    }
}

// 游戏结束
function gameOver() {
    gameState.gameRunning = false;
    clearInterval(gameState.gameLoop);
    finalScoreElement.textContent = gameState.score;
    gameOverModal.style.display = 'block';
}

// 游戏主循环
function gameStep() {
    update();
}

// 开始游戏
function startGame() {
    if (!gameState.gameRunning) {
        gameState.gameRunning = true;
        gameState.gamePaused = false;
        gameState.gameLoop = setInterval(gameStep, config.initialSpeed);
    }
}

// 暂停游戏
function pauseGame() {
    if (gameState.gameRunning && !gameState.gamePaused) {
        gameState.gamePaused = true;
        clearInterval(gameState.gameLoop);
        pauseBtn.textContent = '继续';
    } else if (gameState.gameRunning && gameState.gamePaused) {
        gameState.gamePaused = false;
        gameState.gameLoop = setInterval(gameStep, config.initialSpeed);
        pauseBtn.textContent = '暂停';
    }
}

// 重新开始游戏
function restartGame() {
    clearInterval(gameState.gameLoop);
    initGame();
    startGame();
}

// 键盘控制
document.addEventListener('keydown', (e) => {
    if (!gameState.gameRunning || gameState.gamePaused) return;
    
    switch (e.key) {
        case 'ArrowUp':
            if (gameState.direction !== 'down') {
                gameState.nextDirection = 'up';
            }
            break;
        case 'ArrowDown':
            if (gameState.direction !== 'up') {
                gameState.nextDirection = 'down';
            }
            break;
        case 'ArrowLeft':
            if (gameState.direction !== 'right') {
                gameState.nextDirection = 'left';
            }
            break;
        case 'ArrowRight':
            if (gameState.direction !== 'left') {
                gameState.nextDirection = 'right';
            }
            break;
    }
});

// 事件监听
startBtn.addEventListener('click', () => {
    if (!gameState.gameRunning) {
        startGame();
    }
});

pauseBtn.addEventListener('click', pauseGame);
restartBtn.addEventListener('click', restartGame);
playAgainBtn.addEventListener('click', () => {
    gameOverModal.style.display = 'none';
    restartGame();
});

// 初始化游戏
initGame();
